#ifndef __PROACTOR_H__
#define __PROACTOR_H__

#include <stdio.h>
#include <liburing.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include "public.h"
#include "content_node.h"

// 补充缺失宏定义
#define PA_BUFFER_LENGTH 1024 // 接收临时缓冲区大小
#define EVENT_ACCEPT 0
#define EVENT_RECV 1
#define EVENT_SEND 2
#define ENTRIES_LENGTH 1024


// 连接上下文：用链表管理收发数据
typedef struct proactor_conn
{
    int fd;
    int event;
    int ref_count;  // 引用计数
    int is_closing; // 标记连接是否正在关闭

    char buffer[PA_BUFFER_LENGTH];        // 接收临时缓冲区（单次recv用）
    char remain_buffer[PA_BUFFER_LENGTH]; // 预留：存储半包数据
    int remain_len;

    node remain_link; // 预留：可用于临时存储半包（当前用rlink替代）
    node wlink;       // 发送链表：业务层处理后的响应数据
    node rlink;       // 接收链表：已接收数据（含半包），待拆分处理

    int idx; // 单个发送节点的已发送字节偏移（处理部分发送）

    // accept专用：存储客户端地址信息（仅监听上下文使用）
    struct sockaddr_in *clientaddr;
    socklen_t *addr_len;
} proactor_conn;

proactor_conn *pa_register_conn(int fd, int is_listenfd)
{
    proactor_conn *conn = kvs_malloc(sizeof(proactor_conn));
    if (!conn)
    {
        perror("kvs_malloc new_ctx失败");
        return NULL;
    }

    memset(conn, 0, sizeof(proactor_conn));
    conn->fd = fd;

    conn->idx = 0;
    conn->ref_count = 0;
    conn->is_closing = 0;
     conn->event = EVENT_RECV;
    list_init(&conn->rlink);
    list_init(&conn->wlink);
    list_init(&conn->remain_link);


    if (is_listenfd)
    {
        conn->clientaddr = kvs_malloc(sizeof(struct sockaddr_in));
        conn->addr_len = kvs_malloc(sizeof(socklen_t));

        if (!conn->clientaddr || !conn->addr_len)
        {
            perror("kvs_malloc clientaddr/addr_len失败");
            kvs_free(conn->clientaddr);
            kvs_free(conn->addr_len);
            kvs_free(conn);
            return NULL;
        }
         *(conn->addr_len) = sizeof(struct sockaddr_in);
         conn->event = EVENT_ACCEPT;
    }

    return conn;
}

// 初始化服务端监听套接字
int proactor_init_server(unsigned short port)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        perror("socket创建失败");
        return -1;
    }

    int reuse = 1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
    {
        perror("setsockopt失败");
        close(sockfd);
        return -1;
    }

    struct sockaddr_in serveraddr;
    memset(&serveraddr, 0, sizeof(struct sockaddr_in));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serveraddr.sin_port = htons(port);

    if (-1 == bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(struct sockaddr)))
    {
        perror("bind绑定端口失败");
        close(sockfd);
        return -1;
    }

    if (listen(sockfd, 1024) == -1)
    {
        perror("listen失败");
        close(sockfd);
        return -1;
    }
    return sockfd;
}

// 注册读事件（接收数据）
int set_event_recv(struct io_uring *ring, proactor_conn *conn)
{
    if (conn->is_closing)
    {
        return -1;
    }

    conn->event = EVENT_RECV;
    struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
    if (!sqe)
    {
        perror("获取SQE失败");
        return -1;
    }

    io_uring_prep_recv(sqe, conn->fd, conn->buffer, PA_BUFFER_LENGTH - 1, 0);
    sqe->user_data = (unsigned long)conn;
    conn->ref_count++;

    return 0;
}

// 注册写事件（发送数据）：从发送链表取第一个节点
int set_event_send(struct io_uring *ring, proactor_conn *conn)
{
    if (conn->is_closing)
    {
        return -1;
    }

    conn->event = EVENT_SEND;
    node *send_node = conn->wlink.next;

    if (send_node == &conn->wlink)
    {
        LOG("发送链表为空，注册读事件\n");
        set_event_recv(ring, conn);
        return 0;
    }

    struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
    if (!sqe)
    {
        perror("获取SQE失败");
        return -1;
    }

    char *send_buf = send_node->data + conn->idx;
    int send_len = send_node->length - conn->idx;
    io_uring_prep_send(sqe, conn->fd, send_buf, send_len, 0);
    sqe->user_data = (unsigned long)conn;
    conn->ref_count++;

    // LOG("注册发送事件：fd=%d, 偏移=%d, 长度=%d, ref_count=%d\n", conn->fd, conn->idx, send_len, conn->ref_count);
    return 0;
}

// 注册accept事件（接收新连接）
int set_event_accept(struct io_uring *ring, proactor_conn *conn)
{
    if (conn->is_closing)
    {
        return -1;
    }
    struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
    if (!sqe)
    {
        perror("获取SQE失败");
        return -1;
    }
    conn->event = EVENT_ACCEPT;

    io_uring_prep_accept(sqe, conn->fd, (struct sockaddr *)conn->clientaddr, conn->addr_len, 0);
    sqe->user_data = (unsigned long)conn;
    conn->ref_count++;

    return 0;
}

// 安全释放ctx上下文
void safe_release_conn(proactor_conn *conn)
{
    conn->ref_count--;
    // LOG("释放引用: fd=%d, event=%d, ref_count=%d\n", conn->fd, conn->event, conn->ref_count);

    if (conn->ref_count == 0 && conn->is_closing == 1)
    {
        LOG("连接关闭: fd=%d\n", conn->fd);
        clear_list(&conn->rlink);
        clear_list(&conn->wlink);
        clear_list(&conn->remain_link);
        close(conn->fd);

        if (conn->event == EVENT_ACCEPT)
        {
            kvs_free(conn->clientaddr);
            kvs_free(conn->addr_len);
        }

        kvs_free(conn);
    }
}

int proactor_fill_with_list(char *buffer, int len, node *link)
{
    int idx = strlen(buffer);
    int cpy_len = 0;

    node *node = link->next;
    while (node != link)
    {
        int node_len = node->length;
        if (node_len > len - cpy_len)
        {
            memcpy(buffer + idx + cpy_len, node->data, len - cpy_len);
            cpy_len = len;
            break;
        }
        else
        {
            memcpy(buffer + idx + cpy_len, node->data, node_len);
            cpy_len += node_len;
            node = node->next;
        }
    }
    return cpy_len;
}



#endif